package com.heartech.prediciton_wx.service.token;

import com.google.gson.Gson;
import com.heartech.prediciton_wx.entity.qrcode.QrStrState;
import com.heartech.prediciton_wx.entity.token.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Slf4j
@Service
public class TokenService {
    public AccessToken getAccessToken(String getUrl) {
        AccessToken responseObject = null;

        try {
            URL urlForGetRequest = new URL(getUrl);
            HttpURLConnection con = (HttpURLConnection) urlForGetRequest.openConnection();
            con.setRequestMethod("GET");

            // 添加请求头部
            con.setRequestProperty("Accept", "application/json");

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印响应内容以进行调试
                log.info("Response from the server: " + response.toString());

                // 使用Gson解析JSON数据
                Gson gson = new Gson();
                responseObject = gson.fromJson(response.toString(), AccessToken.class);
                con.disconnect();
            } else {
                log.info("GET request not worked");
                con.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseObject;
    }

}
